// src/components/system-config/ExportVariableManager.jsx
import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { WordExportConfigAPI } from "@/api/WordExportConfig";
import {
  Plus,
  Save,
  Edit,
  Trash2,
  X,
  FileText,
  AlertCircle,
  Loader2,
  ChevronsDown,
  MoreHorizontal,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";

const ExportVariableManager = ({ isLoading: pageIsLoading }) => {
  const [variables, setVariables] = useState([]);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [formData, setFormData] = useState({
    variableName: "",
    variableDesc: "",
    variableType: "TEXT",
    format: "",
    templateId: "",
    status: "0",
    sortOrder: 0,
    dataSourceType: "STATIC",
    dataSourceConfig: '{"staticValue": ""}',
    defaultValue: "",
  });
  const [isLoading, setIsLoading] = useState(false);
  const [saveStatus, setSaveStatus] = useState(null);
  // 分页状态
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [totalItems, setTotalItems] = useState(0);

  // 计算总页数
  const totalPages = Math.max(1, Math.ceil(totalItems / itemsPerPage));

  // 从接口加载导出变量列表（带分页）
  useEffect(() => {
    const fetchVariables = async () => {
      setIsLoading(true);
      try {
        const res = await WordExportConfigAPI.getList({
          page: currentPage,
          pageSize: itemsPerPage,
        });
        setVariables(res.data || []);
        setTotalItems(res.data.length || 0);
      } catch (error) {
        console.error("加载导出变量失败:", error);
        alert("加载导出变量失败，请稍后重试");
      }
      setIsLoading(false);
    };
    fetchVariables();
  }, [currentPage, itemsPerPage]);

  // 处理表单输入变化
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  // 处理数据源配置的JSON输入
  const handleDataSourceConfig = (value) => {
    try {
      JSON.parse(value);
      setFormData((prev) => ({ ...prev, dataSourceConfig: value }));
    } catch (error) {
      alert("请输入有效的JSON格式");
    }
  };

  // 新增变量
  const handleAdd = async () => {
    if (!formData.variableName.trim()) {
      alert("变量名称不能为空");
      return;
    }

    setIsLoading(true);
    setSaveStatus("saving");
    try {
      await WordExportConfigAPI.create(formData);
      setSaveStatus("success");
      // 刷新当前页
      const res = await WordExportConfigAPI.getList({
        page: currentPage,
        pageSize: itemsPerPage,
      });
      setVariables(res.data || []);
      setTotalItems(res.total || 0);
      resetForm();
    } catch (error) {
      console.error("新增变量失败:", error);
      setSaveStatus("error");
      alert(`新增失败: ${error.response?.data?.message || "系统错误"}`);
    }
    setIsLoading(false);
    setTimeout(() => setSaveStatus(null), 3000);
  };

  // 编辑变量
  const handleEdit = (variable) => {
    setEditingId(variable.id);
    setFormData({
      ...variable,
      sortOrder: Number(variable.sortOrder),
      dataSourceConfig: variable.dataSourceConfig || '{"staticValue": ""}',
    });
    setShowForm(true);
  };

  // 更新变量
  const handleUpdate = async () => {
    if (!formData.variableName.trim()) {
      alert("变量名称不能为空");
      return;
    }

    setIsLoading(true);
    setSaveStatus("saving");
    try {
      await WordExportConfigAPI.update(formData.id, formData);
      setSaveStatus("success");
      // 刷新当前页
      const res = await WordExportConfigAPI.getList({
        page: currentPage,
        pageSize: itemsPerPage,
      });
      setVariables(res.data || []);
      resetForm();
    } catch (error) {
      console.error("更新变量失败:", error);
      setSaveStatus("error");
      alert(`更新失败: ${error.response?.data?.message || "系统错误"}`);
    }
    setIsLoading(false);
    setTimeout(() => setSaveStatus(null), 3000);
  };

  // 删除变量
  const handleDelete = async (id) => {
    if (!window.confirm("确定要删除这个导出变量吗？")) return;

    setIsLoading(true);
    try {
      await WordExportConfigAPI.delete(id);
      // 刷新当前页
      const res = await WordExportConfigAPI.getList({
        page: currentPage,
        pageSize: itemsPerPage,
      });
      setVariables(res.data || []);
      setTotalItems((prev) => Math.max(0, prev - 1));

      // 如果删除后当前页为空且不是第一页，自动跳转到上一页
      if (res.data?.length === 0 && currentPage > 1) {
        setCurrentPage((prev) => prev - 1);
      }
    } catch (error) {
      console.error("删除变量失败:", error);
      alert("删除变量失败，请稍后重试");
    }
    setIsLoading(false);
  };

  // 重置表单
  const resetForm = () => {
    setFormData({
      variableName: "",
      variableDesc: "",
      variableType: "TEXT",
      format: "",
      templateId: "",
      status: "0",
      sortOrder: 0,
      dataSourceType: "STATIC",
      dataSourceConfig: '{"staticValue": ""}',
      defaultValue: "",
    });
    setEditingId(null);
    setShowForm(false);
  };

  // 渲染保存状态
  const renderSaveStatus = () => {
    if (!saveStatus) return null;

    const statusConfig = {
      saving: {
        icon: Loader2,
        text: "保存中...",
        color: "text-blue-600",
        bgColor: "bg-blue-50",
      },
      success: {
        icon: Save,
        text: "保存成功",
        color: "text-green-600",
        bgColor: "bg-green-50",
      },
      error: {
        icon: AlertCircle,
        text: "保存失败",
        color: "text-red-600",
        bgColor: "bg-red-50",
      },
    };

    const config = statusConfig[saveStatus];
    const Icon = config.icon;

    return (
      <div
        className={`flex items-center gap-2 px-3 py-2 rounded-lg ${config.bgColor} ${config.color} mb-4`}
      >
        <Icon
          className={`w-4 h-4 ${saveStatus === "saving" ? "animate-spin" : ""}`}
        />
        <span className="text-sm font-medium">{config.text}</span>
      </div>
    );
  };

  // 分页变更处理
  const handlePageChange = (page) => {
    if (page < 1 || page > totalPages) return;
    setCurrentPage(page);
  };

  // 每页条数变更处理
  const handleItemsPerPageChange = (count) => {
    setItemsPerPage(count);
    setCurrentPage(1); // 重置到第一页
  };

  // 渲染分页组件
  const renderPagination = () => (
    <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-4 py-3 border-t">
      <div className="text-sm text-gray-500">
        共 {totalItems} 条数据，显示
        {(currentPage - 1) * itemsPerPage + 1} 到
        {Math.min(currentPage * itemsPerPage, totalItems)} 条
      </div>
      <div className="flex items-center gap-2">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" size="sm" className="h-8">
              每页 {itemsPerPage} 条
              <MoreHorizontal className="ml-2 h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {[5, 10, 20, 50].map((count) => (
              <DropdownMenuItem
                key={count}
                onClick={() => handleItemsPerPageChange(count)}
              >
                {count} 条/页
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
        <div className="flex items-center gap-1">
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage - 1)}
            disabled={currentPage === 1 || isLoading}
          >
            <ChevronLeft className="h-4 w-4" />
            <span className="sr-only">上一页</span>
          </Button>
          {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
            let pageNum;
            if (totalPages <= 5) {
              pageNum = i + 1;
            } else if (currentPage <= 3) {
              pageNum = i + 1;
            } else if (currentPage >= totalPages - 2) {
              pageNum = totalPages - 4 + i;
            } else {
              pageNum = currentPage - 2 + i;
            }
            return (
              <Button
                key={pageNum}
                variant={currentPage === pageNum ? "default" : "outline"}
                size="icon"
                className="h-8 w-8"
                onClick={() => handlePageChange(pageNum)}
                disabled={isLoading}
              >
                {pageNum}
              </Button>
            );
          })}
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage + 1)}
            disabled={currentPage === totalPages || isLoading}
          >
            <ChevronRight className="h-4 w-4" />
            <span className="sr-only">下一页</span>
          </Button>
        </div>
      </div>
    </div>
  );

  return (
    <Card className="shadow-sm">
      <CardHeader className="flex flex-row items-center justify-between">
        <CardTitle className="flex items-center gap-2">
          <FileText className="w-5 h-5 text-blue-600" />
          导出变量管理
        </CardTitle>
        <Button
          onClick={() => {
            resetForm();
            setShowForm(true);
          }}
          size="sm"
          disabled={isLoading || pageIsLoading}
        >
          <Plus className="w-4 h-4 mr-1" /> 添加变量
        </Button>
      </CardHeader>
      <CardContent>
        {renderSaveStatus()}

        {/* 表单区域 */}
        {showForm && (
          <div className="border rounded-lg p-4 mb-6 bg-gray-50">
            <h3 className="text-base font-medium mb-4">
              {editingId ? "编辑导出变量" : "添加导出变量"}
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label htmlFor="var-name">
                  变量名称 <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="var-name"
                  name="variableName"
                  value={formData.variableName}
                  onChange={handleInputChange}
                  placeholder="例如：${projectName}"
                  disabled={isLoading}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="var-desc">变量描述</Label>
                <Input
                  id="var-desc"
                  name="variableDesc"
                  value={formData.variableDesc}
                  onChange={handleInputChange}
                  placeholder="例如：项目名称"
                  disabled={isLoading}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="var-type">变量类型</Label>
                <select
                  id="var-type"
                  name="variableType"
                  value={formData.variableType}
                  onChange={(e) => handleInputChange(e)}
                  className="w-full h-10 border rounded-md px-3 text-sm"
                  disabled={isLoading}
                >
                  <option value="TEXT">文本(TEXT)</option>
                  <option value="TABLE">表格(TABLE)</option>
                  <option value="IMAGE">图片(IMAGE)</option>
                  <option value="FIELD">字段(FIELD)</option>
                </select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="var-templateId">所属模板ID</Label>
                <Input
                  id="var-templateId"
                  name="templateId"
                  value={formData.templateId}
                  onChange={handleInputChange}
                  placeholder="例如：template_001"
                  disabled={isLoading}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="var-status">状态</Label>
                <select
                  id="var-status"
                  name="status"
                  value={formData.status}
                  onChange={(e) => handleInputChange(e)}
                  className="w-full h-10 border rounded-md px-3 text-sm"
                  disabled={isLoading}
                >
                  <option value="0">启用</option>
                  <option value="1">停用</option>
                </select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="var-sortOrder">排序号</Label>
                <Input
                  id="var-sortOrder"
                  name="sortOrder"
                  type="number"
                  value={formData.sortOrder}
                  onChange={handleInputChange}
                  placeholder="输入排序序号"
                  disabled={isLoading}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="var-datasource-type">数据源类型</Label>
                <select
                  id="var-datasource-type"
                  name="dataSourceType"
                  value={formData.dataSourceType}
                  onChange={(e) => handleInputChange(e)}
                  className="w-full h-10 border rounded-md px-3 text-sm"
                  disabled={isLoading}
                >
                  <option value="STATIC">静态值(STATIC)</option>
                  <option value="METHOD">方法调用(METHOD)</option>
                  <option value="FIELD">字段数据(FIELD)</option>
                </select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="var-datasource-config">
                  数据源配置（JSON格式）
                </Label>
                <Textarea
                  id="var-datasource-config"
                  name="dataSourceConfig"
                  value={formData.dataSourceConfig}
                  onChange={(e) => handleDataSourceConfig(e.target.value)}
                  placeholder='例如：{"staticValue": "默认值"}'
                  rows={2}
                  disabled={isLoading}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="var-default-value">默认值</Label>
                <Input
                  id="var-default-value"
                  name="defaultValue"
                  value={formData.defaultValue}
                  onChange={handleInputChange}
                  placeholder="例如：默认项目名称"
                  disabled={isLoading}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="var-format">格式说明</Label>
                <Input
                  id="var-format"
                  name="format"
                  value={formData.format}
                  onChange={handleInputChange}
                  placeholder="例如：YYYY-MM-DD"
                  disabled={isLoading}
                />
              </div>
            </div>

            <div className="flex justify-end gap-3 mt-4">
              <Button
                variant="outline"
                size="sm"
                onClick={resetForm}
                disabled={isLoading}
              >
                <X className="w-4 h-4 mr-1" /> 取消
              </Button>
              <Button
                size="sm"
                onClick={editingId ? handleUpdate : handleAdd}
                disabled={isLoading}
              >
                <Save className="w-4 h-4 mr-1" /> 保存
              </Button>
            </div>
          </div>
        )}

        {/* 变量列表和分页 */}
        {isLoading || pageIsLoading ? (
          <div className="flex justify-center items-center py-12">
            <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
          </div>
        ) : variables.length === 0 ? (
          <div className="text-center py-12 text-gray-500">
            <FileText className="w-12 h-12 mx-auto mb-3 opacity-40" />
            <h4 className="text-base font-medium mb-1">暂无导出变量配置</h4>
            <p className="text-sm max-w-md mx-auto">
              点击"添加变量"按钮创建导出变量，用于系统数据导出时的字段映射
            </p>
          </div>
        ) : (
          <>
            <div className="overflow-x-auto rounded-lg border">
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left font-medium text-gray-600 border-b">
                      变量名称
                    </th>
                    <th className="px-4 py-3 text-left font-medium text-gray-600 border-b">
                      变量类型
                    </th>
                    <th className="px-4 py-3 text-left font-medium text-gray-600 border-b">
                      数据源类型
                    </th>
                    <th className="px-4 py-3 text-left font-medium text-gray-600 border-b">
                      状态
                    </th>
                    <th className="px-4 py-3 text-left font-medium text-gray-600 border-b">
                      描述
                    </th>
                    <th className="px-4 py-3 text-right font-medium text-gray-600 border-b">
                      操作
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {variables.map((variable) => (
                    <tr key={variable.id} className="hover:bg-gray-50">
                      <td className="px-4 py-3 border-b">
                        {variable.variableName}
                      </td>
                      <td className="px-4 py-3 border-b">
                        {variable.variableType}
                      </td>
                      <td className="px-4 py-3 border-b">
                        {variable.dataSourceType}
                      </td>
                      <td className="px-4 py-3 border-b">
                        {variable.status === "0" ? "启用" : "停用"}
                      </td>
                      <td className="px-4 py-3 border-b max-w-xs truncate">
                        {variable.variableDesc || "-"}
                      </td>
                      <td className="px-4 py-3 border-b text-right">
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-8 w-8 p-0"
                            >
                              <MoreHorizontal className="w-4 h-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuItem
                              onClick={() => handleEdit(variable)}
                            >
                              <Edit className="w-4 h-4 mr-2" /> 编辑
                            </DropdownMenuItem>
                            <DropdownMenuItem
                              onClick={() => handleDelete(variable.id)}
                              className="text-red-600"
                            >
                              <Trash2 className="w-4 h-4 mr-2" /> 删除
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* 分页组件 */}
            {renderPagination()}
          </>
        )}
      </CardContent>
    </Card>
  );
};

export default ExportVariableManager;
